package com.fund.client.utils;

import com.fund.client.constants.ClientConstants;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.sql.Date;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class AccountCodeGenerator {

    StringRedisTemplate stringRedisTemplate;

    public AccountCodeGenerator(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //账户生成器,采用时间戳+序列号的方式
    public String getNewAccountCode() {
        //获取距离2025年初的时间戳
        ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
        ZonedDateTime zonedDateTime = ZonedDateTime.of(2025, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
        long timestamp = now.toEpochSecond() - zonedDateTime.toEpochSecond();
        //获取序列号，序列号每日更新
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String date = formatter.format(now);
        Long serialNumber = stringRedisTemplate.opsForValue().increment(ClientConstants.CODE_GENERATOR_PREFIX + date);
        if(serialNumber == null){
            throw new RuntimeException("账户代码生成错误：序列号为null");
        }
        //拼接返回
        return Long.toString(timestamp).concat(String.format("%07d", serialNumber));
    }
}
